package com.eastshop.order.action;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.apache.struts2.ServletActionContext;

import com.eastshop.address.service.AddressService;
import com.eastshop.address.vo.Address;
import com.eastshop.cart.vo.Cart;
import com.eastshop.cart.vo.CartItem;
import com.eastshop.order.service.OrderService;
import com.eastshop.order.vo.Order;
import com.eastshop.order.vo.Orderitem;
import com.eastshop.user.vo.User;
import com.eastshop.utils.PageBean;
import com.eastshop.utils.PaymentUtil;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

/**
 * 订单管理的Action类
 * 
 * @author admin
 */
public class OrderAction extends ActionSupport implements ModelDriven<Order> {
	// 模型驱动使用的对象
	private Order order = new Order();

	public Order getModel() {
		return order;
	}

	// 注入OrderService
	private OrderService orderService;

	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	// 注入AddressService
	private AddressService addressService;

	public void setAddressService(AddressService addressService) {
		this.addressService = addressService;
	}

	// 接收page
	private int page;

	public void setPage(int page) {
		this.page = page;
	}
	
	// 接收支付通道的编码
	private String pd_FrpId;
	
	public void setPd_FrpId(String pd_FrpId) {
		this.pd_FrpId = pd_FrpId;
	}

	// 接收收款成功后的响应数据
	private String r6_Order;
	private String r3_Amt;
	
	public String getR6_Order() {
		return r6_Order;
	}

	public void setR6_Order(String r6_Order) {
		this.r6_Order = r6_Order;
	}

	public String getR3_Amt() {
		return r3_Amt;
	}

	public void setR3_Amt(String r3_Amt) {
		this.r3_Amt = r3_Amt;
	}

	// 保存订单的方法
	public String saveOrder() throws IOException {
		// 1.从session中取出购物车
		Cart cart = (Cart) ServletActionContext.getRequest().getSession()
				.getAttribute("cart");
		if (cart == null || cart.getCartItems().size() == 0) {
			this.addActionMessage("亲，您还没有购物！");
			return "msg";
		}
		// 2.从session中取出登录的用户
		User user = (User) ServletActionContext.getRequest().getSession()
				.getAttribute("existUser");
		if (user == null) {
			this.addActionMessage("亲，您还没有登录！");
			return "msg";
		}
		// 3.补全订单数据
		order.setTotal(cart.getTotal());
		order.setOrdertime(new Date());
		order.setState(0); // 0：未付款
		order.setUser(user);
		// 4.补全订单的订单项
		for (CartItem cartItem : cart.getCartItems()) {
			// 订单项的信息从购物项获得
			Orderitem orderitem = new Orderitem();
			orderitem.setSubtotal(cartItem.getSubtotal());
			orderitem.setCount(cartItem.getCount());
			orderitem.setOrder(order);
			orderitem.setProduct(cartItem.getProduct());
			order.getOrderitems().add(orderitem);
		}
		// 5.保存订单
		Integer oid = orderService.save(order);
		ActionContext.getContext().getValueStack().set("oid", oid);
		// 6.清空购物车
		cart.clearCart();
		// 7.转向查询订单的页面
		return "saveOrder";
	}

	// 分页查询我的订单的方法
	public String findByUidWithPage() {
		User existUser = (User) ServletActionContext.getRequest().getSession()
				.getAttribute("existUser");
		// 根据用户的id分页查询订单
		PageBean<Order> pageBean = orderService.findByUidWithPage(page,
				existUser.getUid());
		// 将查询结果存入值栈
		ActionContext.getContext().getValueStack().set("pageBean", pageBean);
		return "findByUidWithPage";
	}

	// 在线支付的方法
	public String payOrder() throws IOException {
		// 修改订单的信息
		Order currOrder = orderService.findByOid(order.getOid());
		currOrder.setName(order.getName());
		currOrder.setPhone(order.getPhone());
		currOrder.setAddr(order.getAddr());
		orderService.update(currOrder);
		
		// 为订单付款
		String p0_Cmd = "Buy"; // 业务类型
		String p1_MerId = "10001126856"; // 商户编号
		String p2_Order = order.getOid().toString(); // 商户订单号
		String p3_Amt = "0.01"; // 支付金额
		String p4_Cur = "CNY"; // 交易币种
		String p5_Pid = ""; // 商品名称
		String p6_Pcat = ""; // 商品的种类
		String p7_Pdesc = ""; // 商品的描述
		String p8_Url = "http://localhost:8080/eastshop/order_callBack.action";
		String p9_SAF = ""; // 送货地址
		String pa_MP = ""; // 商户扩展信息
		String pd_FrpId = this.pd_FrpId; //支付通道编码
		String pr_NeedResponse = "1"; // 应答机制
		String keyValue = "69cl522AV6q613Ii4W6u8K6XuW8vM1N6bFgyv769220IuYe9u37N4y7rI4Pl";
		String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt, p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP, pd_FrpId, pr_NeedResponse, keyValue);
		
		// 向易宝出发
		StringBuffer sb = new StringBuffer("https://www.yeepay.com/app-merchant-proxy/node?");
		sb.append("p0_Cmd=").append(p0_Cmd).append("&");
		sb.append("p1_MerId=").append(p1_MerId).append("&");
		sb.append("p2_Order=").append(p2_Order).append("&");
		sb.append("p3_Amt=").append(p3_Amt).append("&");
		sb.append("p4_Cur=").append(p4_Cur).append("&");
		sb.append("p5_Pid=").append(p5_Pid).append("&");
		sb.append("p6_Pcat=").append(p6_Pcat).append("&");
		sb.append("p7_Pdesc=").append(p7_Pdesc).append("&");
		sb.append("p8_Url=").append(p8_Url).append("&");
		sb.append("p9_SAF=").append(p9_SAF).append("&");
		sb.append("pa_MP=").append(pa_MP).append("&");
		sb.append("pd_FrpId=").append(pd_FrpId).append("&");
		sb.append("pr_NeedResponse=").append(pr_NeedResponse).append("&");
		sb.append("hmac=").append(hmac);
		
		// 重定向到易宝
		ServletActionContext.getResponse().sendRedirect(sb.toString());
		return NONE;
	}

	// 付款成功后的转向
	public String callBack(){
		// 修改订单状态：修改状态为已经付款
		Order currOrder = orderService.findByOid(Integer.valueOf(r6_Order));
		currOrder.setState(1);
		orderService.update(currOrder);
		// 在页面显示付款成功信息
		this.addActionMessage("订单付款成功： 订单编号："+r6_Order+" 付款的金额："+r3_Amt);
		return "msg";
	}
	
	// 扫码支付
	public String payOrderByCode() {
		// 修改订单的信息
		Order currOrder = orderService.findByOid(order.getOid());
		currOrder.setName(order.getName());
		currOrder.setPhone(order.getPhone());
		currOrder.setAddr(order.getAddr());
		currOrder.setState(1); //1：已付款
		// 更新订单的信息
		orderService.update(currOrder);
		this.addActionMessage("支付成功!");
		return "msg";
	}
	
	// 根据订单id查询订单
	public String findByOid() {
		// 根据订单id查询订单
		order = orderService.findByOid(order.getOid());
		// 从session中取出登录的用户
		User user = (User) ServletActionContext.getRequest().getSession()
				.getAttribute("existUser");
		// 查询要显示的收货地址
		List<Address> addrList = addressService.findByUid(user.getUid());
		// 将结果存入值栈
		ActionContext.getContext().getValueStack().set("addrList", addrList);
		return "findByOid";
	}
	
	// 修改订单的状态
	public String updateState(){
		// 根据oid查找订单
		order = orderService.findByOid(order.getOid());
		// 设置订单的状态
		order.setState(1); //1：已付款
		// 更新订单
		orderService.update(order);
		return NONE;
	}
	
	// 修改订单的状态为"订单结束"
	public String updateStateFor3(){
		// 根据oid查找订单
		order = orderService.findByOid(order.getOid());
		// 设置订单的状态
		order.setState(3);
		// 更新订单
		orderService.update(order);
		return "updateStateFor3";
	}
	
	// 获取订单的状态
	public String getOrderState() throws IOException{
		// 根据oid查找订单
		order = orderService.findByOid(order.getOid());
		if(order.getState() == 1){
			ServletActionContext.getResponse().getWriter().print("1");
		}
		return NONE;
	}
}
